<template>
  <div class="app_content">
    <el-form :inline="true" ref="queryForm" :model="queryParams" class="demo-form-inline" :size="size" v-if="showSearch">
        <el-form-item label="字典名称" prop="dictType">
        <el-input
          v-model="queryParams.dictType"
          placeholder="请输入字典名称"
          clearable
          :disabled="true"
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item label="字典标签" prop="dictLabel">
        <el-input
          v-model="queryParams.dictLabel"
          placeholder="请输入字典标签"
          clearable
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="字典状态"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" @click="querySubmit">
          <component :theme="iconTheme" :size="iconSize" :strokeWidth="iconStrokeWidth" :is="'icon-search'"/>
          搜索</el-button>
        <el-button   @click="resetSubmit">
          <component :theme="iconTheme" :size="iconSize" :strokeWidth="iconStrokeWidth" :is="'icon-redo'"/>
          重置</el-button>
      </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            :size="size"
            @click="handleAdd"
            v-hasRole="['system:dict:add']"
          >
          <component :theme="iconTheme" :size="iconSize" :strokeWidth="iconStrokeWidth" :is="'icon-add-one'"/>
          新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            :size="size"
            :disabled="single"
            @click="handleEdit"
            v-hasRole="['system:dict:edit']"
          >
          <component :theme="iconTheme" :size="iconSize" :strokeWidth="iconStrokeWidth" :is="'icon-edit-one'"/>
          修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            :size="size"
            :disabled="multiple"
            @click="handleDelete"
            v-hasRole="['system:dict:remove']"
          >
          <component :theme="iconTheme" :size="iconSize" :strokeWidth="iconStrokeWidth" :is="'icon-delete-five'"/>
          删除</el-button>
        </el-col>
        <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          :size="size"
          @click="close"
        >
        <component :theme="iconTheme" :size="iconSize" :strokeWidth="iconStrokeWidth" :is="'icon-return'"/>
        关闭</el-button>
      </el-col>
        <!-- <el-col :span="1.5">
          <Export  :dc="true"  :dr="true" :exlData="tableData" :tHead="staticData.ExportHead" :tName="'导出的标题'" ></Export>
        </el-col>
  -->
        <!-- <RightToolbar :showSearch="showSearch" @queryTable="getList" :columns="columns"/> -->
        <RightToolbar :showSearch="showSearch" @queryTable='getList' @showSearchClick='showSearchClick' :columns="columns"/>
      </el-row>
      <el-table :border="$border" v-loading="loading" :data="tableData" :height="maxHeight"  style="width: 100%" @selection-change="handleSelectionChange"  :size="size"
      >
      <el-table-column type="selection" width="55" />
      <el-table-column label="编号" prop="id" show-overflow-tooltip key="id" v-if="columns[0].visible">
        <template #default="scope">{{scope.$index+1}}</template>
        </el-table-column>
      <el-table-column label="字典编码" prop="dictCode" show-overflow-tooltip key="dictCode"  v-if="columns[1].visible"/>
      <el-table-column label="字典标签" prop="dictLabel" show-overflow-tooltip key="dictLabel"  v-if="columns[2].visible"/>
      <el-table-column label="字典键值" prop="dictValue" show-overflow-tooltip key="dictValue"  v-if="columns[3].visible"/>
      <el-table-column label="字典排序" align="center" prop="dictSort"  key="dictSort" v-if="columns[4].visible"/>
      <el-table-column label="状态" align="center" :formatter="statusFormat"  prop="status" key="status" v-if="columns[5].visible">
        <!-- <template #default="scope">
          <dict-tag :options="statusOptions" :value="scope.row.status"/>
        </template> -->
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true"  key="remark" v-if="columns[6].visible"/>
      <el-table-column label="创建时间" prop="createTime" show-overflow-tooltip key="createTime"  v-if="columns[7].visible"/>
      <el-table-column label="操作" fixed="right" align="center"  width="250px">
      <template #default="scope">
        <el-button :size="size" type="success" text @click="handleEdit(scope.row)" v-hasRole="['system:dict:edit']"
          >
          <component :theme="iconTheme" :size="iconSize" :strokeWidth="iconStrokeWidth" :is="'icon-edit-one'"/>
          修改</el-button
          >
          <el-button
          :size="size"
          type="danger"
          text
          @click="handleDelete(scope.row)"
          v-hasRole="['system:dict:remove']"
          >
          <component :theme="iconTheme" :size="iconSize" :strokeWidth="iconStrokeWidth" :is="'icon-delete-five'"/>
          删除</el-button
          >
      </template>
      </el-table-column>
  </el-table>
  <div style="margin-top:10px;position: absolute;right: 0;margin-right:20px">
      <el-pagination
        v-model:currentPage="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 30, 40]"
        :small="small"
        :disabled="disabled"
        :background="background"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
  </div>

  <!-- <el-dialog  v-model="open"  :close-on-click-modal="false" :close-on-press-escape="false" :show-close="false" width="600px" append-to-body draggable :fullscreen="fullscreen">
      <template #header="{titleId, titleClass }">
      <div class="my-header">
        <span :id="titleId" :class="titleClass">{{title}}</span>
        <div>
          <component
        style="cursor:pointer;line-height: 24px;margin-right:10px;"
        v-if="fullscreen==false"
              @click="fullscreen=true"
              class="menu-icon"
              theme="outline"
              size="14"
              strokeWidth="3"
              :is="'icon-full-screen-one'"
            />
            <component
            v-else
        style="cursor:pointer;line-height: 24px;margin-right:10px;"
              @click="fullscreen=false"
              class="menu-icon"
              theme="outline"
              size="14"
              strokeWidth="3"
              :is="'icon-off-screen-one'"
            />
        <component
        style="cursor:pointer;line-height: 24px;"
              @click="cancel"
              class="menu-icon"
              theme="outline"
              size="14"
              strokeWidth="3"
              :is="'icon-close'"
            />
        </div>
        
      </div>
    </template>
    <el-form ref="formDataRef" :model="formData" :rules="rules" label-width="80px" :size="size">
        <el-form-item label="字典类型">
          <el-input v-model="formData.dictType" :disabled="true" />
        </el-form-item>
        <el-form-item label="数据标签" prop="dictLabel">
          <el-input v-model="formData.dictLabel" placeholder="请输入数据标签" />
        </el-form-item>
        <el-form-item label="数据键值" prop="dictValue">
          <el-input v-model="formData.dictValue" placeholder="请输入数据键值" />
        </el-form-item>
        <el-form-item label="样式属性" prop="cssClass">
          <el-input v-model="formData.cssClass" placeholder="请输入样式属性" />
        </el-form-item>
        <el-form-item label="显示排序" prop="dictSort">
          <el-input-number v-model="formData.dictSort" controls-position="right" :min="0" />
        </el-form-item>
        <el-form-item label="回显样式" prop="listClass">
          <el-select v-model="formData.listClass">
            <el-option
              v-for="item in listClassOptions"
              :key="item.value"
              :label="item.label + '(' + item.value + ')'"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div  class="dialog-footer">
        <el-button type="primary" @click="submitForm" :size="size">确 定</el-button>
        <el-button @click="cancel" :size="size">取 消</el-button>
      </div>
    </template>
    </el-dialog> -->
    <el-drawer
      :title="title"
      v-model="open"
      direction="rtl"
      destroy-on-close
      size="50%"
      :close-on-click-modal="false"
    >
    <el-form ref="formDataRef" :model="formData" :rules="rules" label-width="80px" :size="size">
        <el-form-item label="字典类型">
          <el-input v-model="formData.dictType" :disabled="true" />
        </el-form-item>
        <el-form-item label="数据标签" prop="dictLabel">
          <el-input v-model="formData.dictLabel" placeholder="请输入数据标签" />
        </el-form-item>
        <el-form-item label="数据键值" prop="dictValue">
          <el-input v-model="formData.dictValue" placeholder="请输入数据键值" />
        </el-form-item>
        <el-form-item label="样式属性" prop="cssClass">
          <el-input v-model="formData.cssClass" placeholder="请输入样式属性" />
        </el-form-item>
        <el-form-item label="显示排序" prop="dictSort">
          <el-input-number v-model="formData.dictSort" controls-position="right" :min="0" />
        </el-form-item>
        <el-form-item label="回显样式" prop="listClass">
          <el-select v-model="formData.listClass">
            <el-option
              v-for="item in listClassOptions"
              :key="item.value"
              :label="item.label + '(' + item.value + ')'"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div  class="dialog-footer">
          <el-button type="primary" @click="submitForm" :size="size">
          <component :theme="iconTheme" :size="iconSize" :strokeWidth="iconStrokeWidth" :is="'icon-correct'"/>
          确 定</el-button>
        <el-button @click="cancel" :size="size">
          <component :theme="iconTheme" :size="iconSize" :strokeWidth="iconStrokeWidth" :is="'icon-return'"/>
          取 消</el-button>
      </div>
    </template>
  </el-drawer>
  </div>
  
</template>

<script  >
import RightToolbar from '@/components/RightToolbar/index.vue';
import { listData, getData, delData, addData, updateData } from "@/api/system/dict/data";
import { optionselect as getDictOptionselect, getType } from "@/api/system/dict/type";

import { computed, ref ,reactive,onMounted,getCurrentInstance,toRefs, nextTick} from 'vue'
import { useStore } from 'vuex';
import {useRoute,useRouter} from 'vue-router';
import { useI18n } from 'vue-i18n';
import {
Delete,
Edit,
Plus,
} from '@element-plus/icons-vue'

export default defineComponent({
  components:{
    
  },
setup(){
  const { proxy } = getCurrentInstance();//关键代码
  const store = useStore();
  const route=useRoute()
  const router=useRouter()
  const tableRef=ref(null)
  const queryForm=ref(null)
  const formDataRef=ref(null)
  const { t } = useI18n();
  const staticData=reactive({
    formData:{
     
    },
    // 表单校验
    rules: {
      dictLabel: [
        { required: true, message: "数据标签不能为空", trigger: "blur" }
      ],
      dictValue: [
        { required: true, message: "数据键值不能为空", trigger: "blur" }
      ],
      dictSort: [
        { required: true, message: "数据顺序不能为空", trigger: "blur" }
      ]
    },
    maxHeight:store.getters['setting/mode']=='horizontal'?document.body.clientHeight - 265:store.getters['setting/isFullScreen']!=false ?document.body.clientHeight - 360:document.body.clientHeight - 320,
    ids:[],
    dictLabel:[],
    single:true,
    multiple:true,
    showSearch:true,
    background:false,
    disabled :false,
    search:'',
    tableData:[],
    // 日期范围
    dateRange: [],
    // 菜单状态数据字典
    statusOptions: [],
    //是否全屏
    fullscreen:false,
    // 是否显示弹出层
    open: false,
    // 弹出层标题
    title: "",
    // 数据标签回显样式
    listClassOptions: [
        {
          value: "default",
          label: "默认"
        },
        {
          value: "primary",
          label: "主要"
        },
        {
          value: "success",
          label: "成功"
        },
        {
          value: "info",
          label: "信息"
        },
        {
          value: "warning",
          label: "警告"
        },
        {
          value: "danger",
          label: "危险"
        }
      ],
      // 类型数据字典
      typeOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        dictName: undefined,
        dictType: undefined,
        status: undefined
      },
      ExportHead:{

  },
  // 列信息
  columns: [
    { key: 0, label: `编号`, visible: true },
    { key: 1, label: `字典编码`, visible: true },
    { key: 2, label: `字典标签`, visible: true },
    { key: 3, label: `字典键值`, visible: true },
    { key: 4, label: `字典排序`, visible: true },
    { key: 5, label: `状态`, visible: true },
    { key: 6, label: `备注`, visible: true },
    { key: 7, label: `创建时间`, visible: true },
    
  ],
    total:0,
    loading:true, 
   
  })
  const size = computed(() => {
        return store.getters['setting/size'];
  });
  const small =computed(() => {
    return size.value=='small'?true:false
  });

  const visitedRouteList = computed(() => {
        return store.getters['tabsBar/visitedRoutes'];
  });

  const isActive = (route) => {
        return route.path === router.currentRoute.value.path;
      };
    const toLastTag = (latestView) => {
        
        if (latestView) {
          router.push(latestView);
        } else {
          router.push('/');
        }
      };

      const handleTabRemove = async (data) => {
        let view;
        visitedRouteList.value.forEach((item) => {
          if (data.activePath == item.path) {
            view = item;
          }
        });
        
        const { visitedRoutes } = await store.dispatch('tabsBar/delRoute', view);
        if (isActive(view)) {
          toLastTag(data.tarPath);
        }
      };
 
  onMounted(() => {
      proxy.$getDicts("sys_normal_disable").then(response => {
        staticData.statusOptions = response.data;
      });
      const dictId = route.query.dictId;
      proxy.getType(dictId);
      proxy.getTypeList();
    })
 /**
   * 重置表单效验方法
   */
   const resetForm = (formEl) => {
    if (!formEl.value) return
    formEl.value.resetFields()
  }
  const methods = {
     /** 查询字典类型详细 */
    getType(dictId) {
      getType(dictId).then(response => {
        staticData.queryParams.dictType = response.data.dictType;
        staticData.defaultDictType = response.data.dictType;
        proxy.getList();
      });
    },
    /** 查询字典类型列表 */
    getTypeList() {
      getDictOptionselect().then(response => {
        staticData.typeOptions = response.data;
      });
    },
    /** 查询字典数据列表 */
    getList() {
      staticData.loading = true;
      listData(staticData.queryParams).then(response => {
        staticData.tableData = response.rows;
        staticData.total = response.total;
        staticData.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      staticData.open = false;
      proxy.reset();
    },
    // 表单重置
    reset() {
      staticData.formData = {
        dictCode: undefined,
        dictLabel: undefined,
        dictValue: undefined,
        cssClass: undefined,
        listClass: 'default',
        dictSort: 0,
        status: "0",
        remark: undefined
      };
      resetForm(formDataRef)
    },
     // 岗位状态字典翻译
     statusFormat(row, column) {
      const data=proxy.$selectDictLabel(staticData.statusOptions, row.status)
      let stateClass
      // if(data=='正常'){
      //   stateClass='status_success'
      // }else{
      //   stateClass='status_error'
      // }
      console.log("================",data)
      return data;
    },
     /**
      * 显示或隐藏搜索条件
      **/
     showSearchClick(data){
       staticData.showSearch=data
     },
     /** 新增按钮操作 */
     handleAdd() {
      proxy.reset();
      staticData.open = true;
      staticData.title = "添加字典数据";
      staticData.formData.dictType = staticData.queryParams.dictType;
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      staticData.ids = selection.map(item => item.dictCode)
      staticData.dictLabel = selection.map(item => item.dictLabel);
      staticData.single = selection.length!=1
      staticData.multiple = !selection.length
    },
    /** 修改按钮操作 */
    handleEdit(row) {
      proxy.reset();
      const dictCode = row.dictCode || staticData.ids
      getData(dictCode).then(response => {
        staticData.formData = response.data;
        staticData.open = true;
        staticData.title = "修改字典数据";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      formDataRef.value.validate(valid => {
        if (valid) {
          if (staticData.formData.dictCode != undefined) {
            updateData(staticData.formData).then(response => {
             // this.$store.dispatch('dict/removeDict', this.queryParams.dictType);
              proxy.Success("修改成功");
              staticData.open = false;
              proxy.getList();
            });
          } else {
            addData(staticData.formData).then(response => {
              //this.$store.dispatch('dict/removeDict', this.queryParams.dictType);
              proxy.Success("新增成功");
              staticData.open = false;
              proxy.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const dictCodes = row.dictCode || staticData.ids;
      const dictLabel = row.dictLabel || staticData.dictLabel;
      ElMessageBox.confirm('是否确认删除字典标签为"' + dictLabel + '"的数据项？', t('confirm.title'), {
          confirmButtonText: t('btn.confirm'),
          cancelButtonText: t('btn.cancel'),
          type: "warning"
        })
      .then(function() {
        return delData(dictCodes);
      }).then(() => {
        proxy.getList();
        proxy.Success("删除成功");
       // this.$store.dispatch('dict/removeDict', this.queryParams.dictType);
      }).catch(() => {});
      
    },
    
    /** 关闭按钮 */
    close() {
      let data={
        activePath:'/system/dict-data',
        tarPath:'/system/dict'
      }
      handleTabRemove(data)
    },
    resetSubmit(){
      staticData.dateRange=[]
      const dictType= staticData.queryParams.dictType
      queryForm.value.resetFields();
      staticData.queryParams.dictType=dictType
      proxy.getList()
    },
    querySubmit(){
      staticData.queryParams.pageNum = 1;
      proxy.getList()
    },
    handleSizeChange (val) {
      console.log(`${val} items per page`)
      staticData.queryParams.pageSize =val;
      proxy.getList()
    },
    handleCurrentChange(val){
      console.log(`current page: ${val}`)
      staticData.queryParams.pageNum =val;
      proxy.getList()
    }

   }
    return {
      Delete,
      Edit,
      Plus,
      size,
      small,
      queryForm,
      formDataRef,
      ...methods,
      ...toRefs(staticData)
    }
}


})



</script>

<style scoped>
.demo-pagination-block + .demo-pagination-block {
margin-top: 10px;
}
.demo-pagination-block .demonstration {
margin-bottom: 16px;
}
</style>
<style scoped>
.app_content{
  
  margin-top: 30px;
  margin-left: 10px;
}
.mb8{
  margin-bottom: 10px;
}
.tree-border {
    margin-top: 5px;
    width: 100%;
    border: 1px solid #e5e6e7;
    background: #fff none;
    border-radius: 4px;
}
</style>